<script setup lang="ts">
import { NButton, NCard, NForm, NFormItem, NInput, useMessage } from 'naive-ui'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/userStore'
import { Api } from '@/types/Api'
import type { BaseResult } from '@/types/BaseResult'
const router = useRouter()
const { user } = storeToRefs(useUserStore())
const { updateUserInfo } = useUserStore()

const message = useMessage()

const uservo = ref({
  username: '',
  password: '',
})

const loading = ref(false)

const login = () => {
  loading.value = true
  Api.post('/auth', uservo.value, (data: BaseResult) => {
    if (data.success) {
      updateUserInfo(() => {
        loading.value = false
        // 必须是管理员角色
        if (user.value.role != 1) {
          message.error('您不是管理员，无法登录')
          return
        }
        // admin admin_pwd
        message.success('登录成功')
        router.push('/admin/main/welcome')
      })
      return
    }
    loading.value = false
    message.error(data.message)
  })
}
</script>

<template>
  <div class="login-view">
    <NCard title="管理员登录">
      <div>
        <NForm @keyup.enter="login">
          <NFormItem>
            <NInput v-model:value="uservo.username" placeholder="请输入用户名"></NInput>
          </NFormItem>
          <NFormItem>
            <NInput
              show-password-on="click"
              type="password"
              v-model:value="uservo.password"
              placeholder="请输入密码"
            ></NInput>
          </NFormItem>
        </NForm>
      </div>
      <template #action>
        <NButton :loading="loading" type="primary" @click="login">登录</NButton>
      </template>
    </NCard>
  </div>
</template>

<style scoped lang="scss">
.login-view {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  .n-card {
    width: 25vw;
  }
}
</style>
